<?php
/**
 * Handler File Class
 *
 * @author admin <admin@wolive.cc>
 * @email admin@wolive.cc
 * @date 2017/06/01
 */

namespace app\admin\controller;

use app\admin\model\Admins;
use think\Controller;
use think\captcha\Captcha;
use think\config;
use app\Common;
use app\extra\push\Pusher;


/**
 * 登录控制器.
 */
class Login extends Controller
{

    /**
     * 登陆首页.
     *
     * @return string
     */
    public function index()
    {

        // 未登陆，呈现登陆页面.
        $params = [];
        $goto = $this->request->get('goto', '');
        if ($goto) {
            $params['goto'] = urlencode($goto);
        }

        $common = new Common();
        $this->assign('submit', url('check', $params));
        $this->assign('mobile', $common->isMobile());

        return $this->fetch();
    }

    /**
     * 注册页面.
     *
     * @return mixed
     */
    public function sign()
    {
        return $this->fetch();
    }


    /**
     * 验证码.
     *
     * @return \think\Response
     */
    public function captcha()
    {

        $captcha = new Captcha(Config::get('captcha'));
        return $captcha->entry('admin_login');
    }

    /**
     * 注册验证码.
     *
     * @return \think\Response
     */
    public function captchaForAdmin()
    {
        $captcha = new Captcha(Config::get('captcha'));
        return $captcha->entry('admin_regist');
    }

    /**
     * 检查.
     *
     * @return void
     */
    public function check()
    {

        $post = $this->request->post();
        if (!isset($post['username']) || !isset($post['password'])) {
            $this->error('参数不完整!', url("/admin/login/index"));
        }

        $post['user_name'] = (trim($post['username']));

        if ($post['user_name'] == "test") {

            $data = Admins::table('wolive_service')->where('user_name', $post['user_name'])->find();
            if (!$data) {
                $this->error('没有这个用户', url("/admin/login/index"));
            }
        } else {

            $post["password"] = ($post['password']);
            unset($post['username']);

            $result = $this->validate($post, 'Login');
            if ($result !== true) {
                $this->error($result);
            }
            // 获取信息 根据$post['username'] 的数据 来做条件 获取整条信息
            $admin = Admins::table("wolive_service")->where('user_name', $post['user_name'])->find();
            if (!$admin) {
                $this->error("用户不存在");
            }
            // 密码检查

            $pass = md5($post['user_name'] . "wolive" . $post['password']);

            $password = Admins::table("wolive_service")->where('password', $pass)->find();

            if (!$password) {

                $this->error('密码错误');
            }

            // 获取登陆数据

            $login = $admin->getData();

            // 删掉登录用户的敏感信息
            unset($login['password']);

            $res = Admins::table('wolive_service')->where('service_id', $login['service_id'])->update(['state' => 'online']);

            $data = Admins::table('wolive_service')->where('service_id', $login['service_id'])->find();

            $budiness = Admins::table('wolive_business')->where('business_id', $data['business_id'])->find();
            // 如果开启了过期配置，检查账户是否过期
            $exclude = ['admin', 'test', 'wolive'];
            if (!in_array($login['business_id'], $exclude)) {
                $time = time();
                $diff = $time - $budiness['exp_timestamp'];
                if ($diff > 0) {
                    $this->error('该测试账户已经过期，请到wolive.cc购买授权');
                }
            }

            if ($budiness['state'] != 'open') {
                $this->error('该账户已经被禁用');
            }

        }

        $_SESSION['Msg'] = $data->getData();

        $common = new Common();

        $ismoblie = $common->isMobile();

        if ($ismoblie) {

            $this->success('登录成功', url("mobile/admin/index"));
        } else {

            $this->success('登录成功', url("admin/Index/index"));
        }

    }

    /**
     *  注册用户.
     *
     * @return string
     */
    public function regist()
    {

        $post = $this->request->post();

        $post['user_name'] = (trim($post['user_name']));
        $post["password"] = ($post['password']);
        $post["password2"] = ($post['password2']);
        $post['nick_name'] = "管理员" . $post['user_name'];
        unset($post['username']);
        unset($post['nickname']);

        $result = $this->validate($post, 'Admins');
        if (true !== $result) {
            return $this->error($result);
        }

        $res = Admins::table('wolive_service')->where('user_name', $post['user_name'])->find();

        if ($res) {
            return $this->error("用户名存在！");
        }
        //合成新函数
        $post['business_id'] = $post['user_name'];

        unset($post['captcha']);
        unset($post['password2']);

        $pass = md5($post['user_name'] . "wolive" . $post['password']);
        $post['password'] = $pass;
        $post['level'] = 'manager';

        Admins::table('wolive_service')->insert($post);

        $exp_time = \think\Config::get('wolive_expire');
        $exp_time = $exp_time ? $exp_time : 10*365*24*60*60;
        $data = ['business_id' => $post['user_name'], 'regist_timestamp' => time()];
        $data['exp_timestamp'] = time() + $exp_time;
        Admins::table('wolive_business')->insert($data);

        return $this->success('注册成功');
    }


    /**
     * 退出登陆 并清除session.
     *
     * @return void
     */
    public function logout()
    {
        if (isset($_SESSION['Msg'])) {
            $login = $_SESSION['Msg'];
            // 更改状态

            setCookie("cu_com", "", time() - 60);
            $_SESSION['Msg'] = null;
        }


        $this->redirect(url('admin/login/index'));

    }

    /**
     * socket_auth 验证
     * [auth description]
     * @return [type] [description]
     */
    public function auth()
    {
        $post = $this->request->post();

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );


        $data = $pusher->socket_auth($post['channel_name'], $post['socket_id']);

        return $data;
    }

}
